import 'dart:async';
import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:jd_flutter/base/foundation/flutter_extension.dart';
import 'package:jd_flutter/base/net/jd_request.dart';

import '../../foundation/jd_colors.dart';

//oss网络图片url前缀
const String kOssImg = ''; // oss图片
const String testUrl =
    'https://upload-images.jianshu.io/upload_images/4344841-c57f374e424234a7.jpg';

getRandomImageUrl() {
  List<String> urlList = [
    r'https://upload-images.jianshu.io/upload_images/2016273-c2266bc919cea6bd.jpg',
    r'https://upload-images.jianshu.io/upload_images/2016273-cb2cd9c857ad3e7a.jpeg',
    r'https://upload-images.jianshu.io/upload_images/2016273-53a3752e06796e2a.jpeg',
    testUrl,
    r'https://upload-images.jianshu.io/upload_images/25923571-05af42b1561aa9b1.png',
    r'https://upload-images.jianshu.io/upload_images/18898562-9413bf9be8114ad6.jpg',
  ];
  int randomIndex = Random().nextInt(urlList.length);
  return urlList[randomIndex];
}

class JDNetworkImage extends StatelessWidget {
  final String url;
  final double? width;
  final double? height;
  // 设置size后不用宽高
  final Size? size;

  final BoxFit? fit;

  /// 圆角 [borderRadius]为[Null]有效
  final double? radius;
  final BorderRadius? borderRadius;
  final double? borderWidth;
  final Color? borderColor;
  final ColorFilter? colorFilter;

  /// 占位图
  final Widget? placeHolder;
  final Widget? placeHolderError;

  const JDNetworkImage({
    Key? key,
    required this.url,
    this.size,
    this.width,
    this.height,
    this.fit,
    this.radius,
    this.borderWidth,
    this.borderColor,
    this.borderRadius,
    this.colorFilter,
    this.placeHolder,
    this.placeHolderError,
  }) : super(key: key);

  const JDNetworkImage.oss({
    Key? key,
    required String url,
    this.width,
    this.height,
    this.size,
    this.fit,
    this.radius,
    this.borderWidth,
    this.borderColor,
    this.borderRadius,
    this.colorFilter,
    this.placeHolder,
    this.placeHolderError,
  })  : url = '$kOssImg$url',
        super(key: key);

  static Future<ImageInfo> preloadOss(String url) {
    return preload('$kOssImg$url');
  }

  static Future<ImageInfo> preload(String url) {
    final completer = Completer<ImageInfo>();
    final imageStream =
        CachedNetworkImageProvider(url).resolve(ImageConfiguration.empty);
    imageStream.addListener(
        ImageStreamListener((ImageInfo image, bool synchronousCall) {
      completer.complete(image);
    }, onError: (Object exception, StackTrace? stackTrace) {
      completer.completeError(exception, stackTrace);
    }));
    return completer.future;
  }

  @override
  Widget build(BuildContext context) {
    final String realUrl;
    if (url == '' || url == 'null') {
      if (placeHolderError != null) return placeHolderError!;
      return _buildPlaceholder();
    } else if (url.startsWith('http')) {
      realUrl = url;
    } else {
      if (url.startsWith('/')) {
        realUrl = '${JDApiRequest.apiServiceUrl}$url';
      } else {
        realUrl = '${JDApiRequest.apiServiceUrl}/$url';
      }
    }
    return CachedNetworkImage(
      imageUrl: realUrl,
      width: size?.width ?? width,
      height: size?.height ?? height,
      fadeInCurve: Curves.easeIn,
      fadeOutCurve: Curves.easeOut,
      fadeOutDuration: const Duration(milliseconds: 125),
      fadeInDuration: const Duration(milliseconds: 125),
      fit: fit ?? BoxFit.cover,
      placeholder: (BuildContext context, String url) {
        if (placeHolder != null) return placeHolder!;
        return _buildPlaceholder();
      },
      errorWidget: (BuildContext context, String url, dynamic error) {
        if (placeHolderError != null) return placeHolderError!;
        return _buildPlaceholder();
      },
      imageBuilder: (context, imageProvider) {
        return Container(
          width: width,
          height: height,
          decoration: BoxDecoration(
            border: borderWidth == null
                ? null
                : Border.all(color: borderColor!, width: borderWidth!),
            borderRadius: borderRadius ?? BorderRadius.circular(radius ?? 0),
            image: DecorationImage(
                image: imageProvider,
                colorFilter: colorFilter,
                fit: fit ?? BoxFit.cover),
          ),
        );
      },
    );
  }

  Container _buildPlaceholder() {
    return Container(
      width: width,
      height: height,
      decoration: BoxDecoration(
        borderRadius: borderRadius ?? BorderRadius.circular(radius ?? 0),
        color: JDColors.cF1F1F1,
        border: borderWidth == null
            ? null
            : Border.all(color: borderColor!, width: borderWidth!),
      ),
    );
  }
}

class JDBackgroundContainer extends StatelessWidget {
  final Widget? backgroundWidget;
  final Container container;

  const JDBackgroundContainer(
      {super.key, this.backgroundWidget, required this.container});

  @override
  Widget build(BuildContext context) {
    return Stack(children: [backgroundWidget ?? Gap.empty, container]);
  }
}

/// 间隔
class Gap {
  static const Widget line = Divider();

  static const Widget vLine = SizedBox(
    width: 0.6,
    height: 24.0,
    child: VerticalDivider(),
  );

  static const Widget empty = SizedBox.shrink();

  static EdgeInsets get padding =>
      EdgeInsets.fromLTRB(12.dp, 15.dp, 12.dp, 15.dp);
}
